/* 购物车脚本
 ** 2020-10-10
 ** by Molly
 */
var mainVm = new Vue({
  el: '.page-container',
  data: {
    loadFlag: true,
    url: {
      cart_list: '/antacom/data.cart/listing',
      cart_update: '/antacom/data.cart/update',
      cart_delete: '/antacom/data.cart/delete',
      cart_submit: '/antacom/data.cart/snapshot',
      path_login: MALL.Common.url.path_login,
      path_reg: MALL.Common.url.path_reg,
      path_torder: MALL.Common.url.path_torder,
    },
    check_all: 0,
    cart: {
      pros: [],
      unable: [],
      info: {
        totalNum: 0,
        totalPrice: '0.00',
      },
    },
    userInfoInCart: false,
  },
  mounted: function () {
    this.loadList();
  },
  methods: {
    loadList: function (data) {
      var that = this,
        _data = {};
      if (data) _data = data;
      if (that.loadFlag == false) return;
      that.loadFlag = false;
      MALL.Common.showLoading();
      $.ajax({
        type: 'POST',
        url: that.url.cart_list,
        async: false,
        data: _data,
        dataType: 'json',
        success: function (res) {
          MALL.Common.hideLoading();
          that.loadFlag = true;
          if (res && res.status == 1) {
            var _pros = [],
              _unable = [],
              _info = { totalNum: 0, totalPrice: '0.00' },
              _check_num = 0;
            for (var x in res.data.list) {
              var _item = res.data.list[x];
              //onsell：0 下架 1在架(stock:库存) 2售罄 3即将开售；
              //status:0 下架 1在架 2售罄 3即将开售
              _item.status = _item.onsell;
              if (_item.status == 1 && parseInt(_item.stock) <= 0) _item.status = 2;
              if (_item.status == 1) {
                _item.checked = 0;
                _item.num = _item.add_num;
                _pros.push(_item);
              } else {
                _unable.push(_item);
              }
              _info.totalNum += parseInt(_item.add_num) >= 0 ? parseInt(_item.add_num) : 0;
            }
            that.$set(that.cart, 'pros', _pros);
            that.$set(that.cart, 'unable', _unable);
            that.$set(that.cart, 'info', _info);
            that.check_all = _check_num == _pros.length && _check_num != 0 ? 1 : 0;
            return false;
          }
        },
        error: function (res) {
          MALL.Common.hideLoading();
          that.loadFlag = true;
        },
      });
    },
    checkOne: function (e, id) {
      var _pros = this.cart.pros;
      for (var x in _pros) {
        if (_pros[x].id_c == id) {
          _pros[x].checked = _pros[x].checked == 1 ? 0 : 1;
        }
      }
      this.$set(this.cart, 'pros', _pros);
      this.changeTotal();
    },
    checkAll: function (e) {
      var _pros = this.cart.pros;
      for (var x in _pros) {
        _pros[x].checked = this.check_all;
      }
      this.$set(this.cart, 'pros', _pros);
      this.changeTotal();
    },
    removeOne: function (id) {
      var _pros = this.cart.pros,
        _newpro = [],
        ids = [];
      for (var x in _pros) {
        if (_pros[x].id_cn != id) _newpro.push(_pros[x]);
      }
      ids.push(id);
      this.deleteGoods(ids, 'pros', _newpro);
    },
    removeChecks: function () {
      var _pros = this.cart.pros,
        _newpro = [],
        ids = [];
      for (var x in _pros) {
        if (_pros[x].checked == 1) {
          ids.push(_pros[x].id_cn);
        } else {
          _newpro.push(_pros[x]);
        }
      }
      if (ids.length == 0) {
        MALL.Common.message({ text: '当前未选中商品', time: 2000 });
        return false;
      }
      this.deleteGoods(ids, 'pros', _newpro);
    },
    clearDisable: function () {
      var _unable = this.cart.unable,
        _newpro = [],
        ids = [];
      for (var x in _unable) {
        ids.push(_unable[x].id_cn);
      }
      this.deleteGoods(ids, 'unable', _newpro, '确认清除失效商品？');
    },
    deleteGoods: function (ids, key, newpro, tips) {
      var that = this;
      MALL.Common.confirm({
        title: tips ? tips : '确认删除选中商品？',
        yes: function () {
          if (that.loadFlag == false) return;
          that.loadFlag = false;
          MALL.Common.showLoading();
          $.ajax({
            type: 'POST',
            url: that.url.cart_delete,
            data: { id_cn: ids.join(',') },
            dataType: 'json',
            success: function (res) {
              MALL.Common.hideLoading();
              that.loadFlag = true;
              if (res.status == 1) {
                that.$set(that.cart, key, newpro);
                that.changeTotal();
                return false;
              }
              MALL.Common.message({ text: res.msg ? res.msg : '商品删除失败，请重试', time: 2000 });
            },
            error: function (res) {
              MALL.Common.hideLoading();
              that.loadFlag = true;
              MALL.Common.message({ text: '商品删除失败，请重试', time: 2000 });
            },
          });
        },
      });
    },
    changeNumByBtn: function (id, type) {
      var _num1,
        _num2,
        _pros = this.cart.pros;
      for (var x in _pros) {
        if (_pros[x].id_cn != id) continue;
        _num1 = parseInt(_pros[x].add_num);
      }
      switch (type) {
        case 1:
          _num2 = _num1 - 1;
          break;
        case 2:
          _num2 = _num1 + 1;
          break;
      }
      if (_num2 <= 0) {
        MALL.Common.message({ text: '不能再少了', time: 2000 });
        return false;
      }
      this.changeNum(id, _num1, _num2);
    },
    changeNumByInput: function (e, id) {
      var _num1,
        _num2,
        _pros = this.cart.pros,
        r = /^\+?[1-9][0-9]*$/,
        _idx;
      for (var x in _pros) {
        if (_pros[x].id_cn != id) continue;
        _num1 = parseInt(_pros[x].num);
        _idx = x;
      }
      _num2 = e.target.value;
      if (!r.test(_num2)) {
        MALL.Common.message({ text: '请输入大于0的整数', time: 2000 });
        _pros[_idx].add_num = _pros[_idx].num;
        this.$set(this.cart, 'pros', _pros);
        return false;
      }
      this.changeNum(id, _num1, _num2);
    },
    changeNum: function (id, num1, num2) {
      MALL.Common.showLoading();
      var that = this,
        _idx,
        _pros = this.cart.pros;
      for (var x in _pros) {
        if (_pros[x].id_cn == id) {
          _idx = x;
          break;
        }
      }
      if (num1 > 0 && num1 == num2) {
        MALL.Common.hideLoading();
        return;
      }
      if (num2 > parseInt(_pros[_idx].stock)) {
        MALL.Common.message({ text: '库存不足', time: 2000 });
        if (num1 > parseInt(_pros[_idx].stock)) {
          num2 = parseInt(_pros[_idx].stock);
        } else {
          _pros[_idx].add_num = _pros[_idx].num;
          that.$set(that.cart, 'pros', _pros);
          MALL.Common.hideLoading();
          return;
        }
      }
      setTimeout(function () {
        if (that.loadFlag == false) {
          MALL.Common.hideLoading();
          return;
        }
        that.loadFlag = false;
        $.ajax({
          type: 'POST',
          url: that.url.cart_update,
          data: { id_cn: id, add_num: num2 },
          dataType: 'json',
          success: function (res) {
            MALL.Common.hideLoading();
            that.loadFlag = true;
            if (res.status == 1) {
              _pros[_idx].add_num = num2;
              _pros[_idx].num = num2;
              that.$set(that.cart, 'pros', _pros);
              that.changeTotal();
              return false;
            }
            MALL.Common.message({ text: res.msg ? res.msg : '数量更新失败，请重试', time: 2000 });
            _pros[_idx].add_num = _pros[_idx].num;
            that.$set(that.cart, 'pros', _pros);
          },
          error: function (res) {
            MALL.Common.hideLoading();
            that.loadFlag = true;
            MALL.Common.message({ text: '数量更新失败，请重试', time: 2000 });
            _pros[_idx].add_num = _pros[_idx].num;
            that.$set(that.cart, 'pros', _pros);
          },
        });
      }, 1000);
    },
    changeTotal: function () {
      var _price = 0,
        _total = 0,
        _info = this.cart.info,
        _pros = this.cart.pros,
        _check_num = 0;
      for (var x in _pros) {
        _total += parseFloat(_pros[x].add_num);
        if (_pros[x].checked == 0) continue;
        _check_num++;
        _price += parseFloat(_pros[x].add_num) * parseFloat(_pros[x].cache_price);
      }
      _info.totalPrice = _price.toFixed(2);
      _info.totalNum = _total || 0;
      this.$set(this.cart, 'info', _info);
      this.check_all = _check_num == _pros.length && _check_num != 0 ? 1 : 0;
      try {
        if (_total > 0) {
          headerVm.cartNum = _total > 99 ? '99+' : _total;
          //   $('.topbar-cart')
          // 	.addClass('notempty')
          // 	.find('i')
          // 	.html(_total > 99 ? '99+' : _total);
        } else {
          headerVm.cartNum = 0;
          //   $('.topbar-cart').removeClass('notempty').find('i').html('');
        }
      } catch (error) {
        console.error(error);
      }
    },
    submitSettle: function () {
      var _idcns = [],
        that = this,
        _pros = this.cart.pros,
        errMsg = '';
      for (var x in _pros) {
        if (_pros[x].checked == 0) continue;
        if (_pros[x].checked == 1 && _pros[x].stock < _pros[x].add_num) errMsg = '当前商品库存不足';
        _idcns.push(_pros[x].id_cn);
      }
      if (errMsg == '' && _idcns.length == 0) errMsg = '当前未选中商品';
      if (errMsg != '') {
        MALL.Common.message({ text: errMsg, time: 2000 });
        return;
      }
      if (that.loadFlag == false) return;
      that.loadFlag = false;
      MALL.Common.showLoading();
      $.ajax({
        type: 'POST',
        url: that.url.cart_submit,
        data: { id_cn_data: _idcns.join(',') },
        dataType: 'json',
        success: function (res) {
          MALL.Common.hideLoading();
          that.loadFlag = true;
          if (res.status == -1) {
            MALL.Common.message({ text: '请先登录', time: 1000 });
            setTimeout(function () {
              location.href = that.url.path_login;
            }, 1000);
            return false;
          }
          if (res.status == 1) {
            location.href = that.url.path_torder + '?snap=' + res.data.snap;
            return false;
          }
          MALL.Common.message({ text: res.msg ? res.msg : '提交失败，请重试', time: 2000 });
          if (res.code == 0 && res.msg && res.msg.indexOf('未登录') >= 0) {
            setTimeout(function () {
              location.href = that.url.path_login;
            }, 1500);
          }
        },
        error: function (res) {
          MALL.Common.hideLoading();
          that.loadFlag = true;
          MALL.Common.message({ text: '提交失败，请重试', time: 2000 });
        },
      });
    },
  },
});
window.onload = function () {
  pageResizeInit();
};
function pageResizeInit() {
  /* 页面窗口resize时调用函数，各页面内重新写并覆盖
   ** ！！！ mall.common.js中的window.onresize函数已调用
   */
}
